from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, desc
from typing import List
from app.database import get_db
from app.models import Conversation, KnowledgeBase, User
from app.schemas import ConversationCreate, ConversationResponse
from app.core.deps import get_current_active_user
from app.core.logging import logger

router = APIRouter(prefix="/conversations", tags=["conversations"])

@router.post("/", response_model=ConversationResponse)
async def create_conversation(
    conversation: ConversationCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建对话记录"""
    logger.info(f"用户 {current_user.username} 创建对话记录")
    
    # 验证知识库是否存在且属于当前用户
    result = await db.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.id == conversation.knowledge_base_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    knowledge_base = result.scalar_one_or_none()
    if not knowledge_base:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Knowledge base not found or access denied"
        )
    
    db_conversation = Conversation(
        **conversation.dict(),
        user_id=current_user.id
    )
    
    db.add(db_conversation)
    await db.commit()
    await db.refresh(db_conversation)
    
    logger.info(f"对话记录创建成功: {db_conversation.id}")
    return db_conversation

@router.get("/", response_model=List[ConversationResponse])
async def get_conversations(
    knowledge_base_id: int = None,
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取对话记录列表"""
    logger.info(f"用户 {current_user.username} 获取对话记录列表")
    
    query = select(Conversation).join(KnowledgeBase).where(KnowledgeBase.user_id == current_user.id)
    
    if knowledge_base_id:
        query = query.where(Conversation.knowledge_base_id == knowledge_base_id)
    
    query = query.order_by(desc(Conversation.created_at)).offset(skip).limit(limit)
    result = await db.execute(query)
    
    conversations = result.scalars().all()
    return conversations

@router.get("/{conversation_id}", response_model=ConversationResponse)
async def get_conversation(
    conversation_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取指定对话记录"""
    logger.info(f"用户 {current_user.username} 获取对话记录 {conversation_id}")
    
    result = await db.execute(
        select(Conversation)
        .join(KnowledgeBase)
        .where(Conversation.id == conversation_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    conversation = result.scalar_one_or_none()
    if not conversation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Conversation not found"
        )
    
    return conversation

@router.delete("/{conversation_id}")
async def delete_conversation(
    conversation_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除对话记录"""
    logger.info(f"用户 {current_user.username} 删除对话记录 {conversation_id}")
    
    result = await db.execute(
        select(Conversation)
        .join(KnowledgeBase)
        .where(Conversation.id == conversation_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    conversation = result.scalar_one_or_none()
    if not conversation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Conversation not found"
        )
    
    await db.delete(conversation)
    await db.commit()
    
    logger.info(f"对话记录删除成功: {conversation_id}")
    return {"message": "Conversation deleted successfully"}